import React, { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import NavBar from "@/components/NavBar/NavBar";
import { Tabs, Toast } from "antd-mobile";
import { fetchCommentListThunk, fetchCommentTotalThunk } from "@/store/modules/commentStore";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { CommentListParams } from "@/type/CommentType";
import EvaluateItem from "@/components/EvaluateItem/EvaluateItem";
import "./CommentList.scss";

const CommentList = () => {
   const navigate = useNavigate();
   const enhanceDispatch = useEnhanceDispatch();
   const [searchParams, setSearchParams] = useSearchParams();

   // 商品评价总数
   const commentTotal = useEnhanceSelector(state => state.commentStore.commentTotal);
   // 商品评价列表
   const commentList = useEnhanceSelector(state => state.commentStore.commentList);
   // 商品ID
   const goodsId: string = searchParams.get("goodsId") as string;
   // 获取商品评价列表的参数
   const [params, setParams] = useState<CommentListParams>({
      goodsId,
      page: 1,
      scoreType: -1,
   });

   /**
    * @description 获取商品评价总数的回调函数
    * */
   const fetchCommentTotal = async () => {
      try {
         await enhanceDispatch(fetchCommentTotalThunk(goodsId)).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 获取商品评价列表的回调函数
    * */
   const fetchCommentList = async () => {
      try {
         await enhanceDispatch(fetchCommentListThunk(params)).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * 修改激活项的回调函数
    * */
   const changeActiveKey = (activeKey: string) => {
      setParams({ ...params, scoreType: Number(activeKey) });
   };

   useEffect(() => {
      fetchCommentTotal();
   }, []);

   useEffect(() => {
      fetchCommentList();
   }, [params]);
   return (
      <div className="comment-list-container">
         <div className="comment-header">
            <NavBar children="商品评价" backIcon onBack={() => navigate(-1)}></NavBar>
            <Tabs activeKey={params.scoreType + ""} onChange={changeActiveKey}>
               <Tabs.Tab title={`全部(${commentTotal.all || 0})`} key={-1}></Tabs.Tab>
               <Tabs.Tab title={`好评(${commentTotal.praise || 0})`} key={10}></Tabs.Tab>
               <Tabs.Tab title={`中评(${commentTotal.review || 0})`} key={20}></Tabs.Tab>
               <Tabs.Tab title={`差评(${commentTotal.negative || 0})`} key={30}></Tabs.Tab>
            </Tabs>
         </div>
         <div className="comment-list">
            {
               commentList.map((item, index) => <EvaluateItem comment={item} key={index}></EvaluateItem>)
            }
         </div>

      </div>
   );
};

export default CommentList;
